package com.ruoyi.framework.datasource;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.ToolUtils;
import com.ruoyi.common.utils.spring.SpringUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

public class DataSourceUtils {

    public static final String MYSQL = "MySQL";
    public static final String SQLITE = "SQLite";

    /**
     * 获取数据库类型
     */

    public static String getDbType() {
        String dbType = null;

        // 从缓存获取
        Object dbTypeObj = CacheUtils.get(Constants.DB_TYPE);
        if (ToolUtils.isNotEmpty(dbTypeObj)) {
            return dbType = String.valueOf(dbTypeObj);
        }

        // 从连接获取
        try {
            DataSource dataSource = SpringUtils.getBean(DataSource.class);
            // 使用 try-with-resources 来确保连接会被关闭
            try (Connection connection = dataSource.getConnection()) {
                if (connection != null) {
                    DatabaseMetaData metaData = connection.getMetaData();
                    if (metaData != null) {
                        dbType = metaData.getDatabaseProductName();
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 存储到缓存
        if (ToolUtils.isNotEmpty(dbType)) {
            CacheUtils.put(Constants.DB_TYPE, dbType);
        }
        return dbType;
    }
}
